// Created by Joe on 2017/6/10.

app.controller(
    'HomeController',
    [
        'KEY', 'ins.helper', 'config', '$scope', '$location', 'UserService', 'AccessTokenService',
        function (KEY, Helper, config, $scope, $location, UserService, AccessTokenService) {
            init();

            function init() {
                // set entry
                $scope.entry = config.HomeEntry;

                // bind popup panel setting
                $scope.panel = {show: false};
                $scope.panelControl = {
                    register: {
                        title: '使用该应用需要您进行登录',
                        button: [
                            {name: '立即登录', action: popupAction()},
                            {
                                name: '取消登录', action: function () {
                            }
                            }
                        ]
                    },
                    certification: {
                        title: '使用该应用需要您实名认证',
                        button: [
                            {name: '立即认证', action: popupAction()},
                            {
                                name: '取消认证', action: function () {
                            }
                            }
                        ]
                    }
                };
                $scope.curPanelControl = $scope.panelControl.register;

                // set focus
                $scope.focus = {currentId: 1};

                // enable exit third app
                // setUser();

                // control user status
                $scope.user = {
                    phone: UserService.user.phone,
                    status: !UserService.user.phone ? 0 : !UserService.user.certification ? 1 : 2
                };
                // set cache
                $scope.cache = {focus: config.cacheNS + '_home'};
                Helper.opStorage($scope).get($scope.cache.focus, 'focus', true);

                // preload access-token
                // AccessTokenService.getAccessToken();

                // ele action
                $scope.move = function (evt) {
                    evt.preventDefault();
                    if ($scope.panel.show)
                        return false;
                    switch (evt.keyCode) {
                        case KEY.LEFT:
                            moveShim('left');
                            break;
                        case KEY.UP:
                            moveShim('up');
                            break;
                        case KEY.RIGHT:
                            moveShim('right');
                            break;
                        case KEY.DOWN:
                            moveShim('down');
                            break;
                        case KEY.ENTER:
                            detect(evt, function () {
                                Helper.opStorage($scope).set($scope.cache.focus, $scope.focus);
                                route($scope.entry[$scope.focus.currentId]['url']);
                            });
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
            }

            function route(url) {
                if (url.indexOf('$') !== -1) {
                    // deal with third app, such as $../demo/index.html
                    location.href = url.replace('$', '') + '?user=' + JSON.stringify(UserService.user);
                } else if (url && url !== '#') {
                    $location.path(url).replace();
                }
            }

            function detect(evt, cb) {
                // 0: no-auth, 1: login, 2: certification
                evt.stopPropagation();
                if ($scope.entry[$scope.focus.currentId].auth === 1 && !UserService.user.phone) {
                    $scope.curPanelControl = $scope.panelControl.register;
                    $scope.panel.show = true;
                    return false;
                } else if ($scope.entry[$scope.focus.currentId].auth === 2 && !UserService.user.certification) {
                    $scope.curPanelControl = $scope.panelControl.certification;
                    $scope.panel.show = true;
                    return false;
                } else {
                    cb instanceof Function && cb();
                }
            }

            function popupAction() {
                return function () {
                    Helper.opStorage($scope).set($scope.cache.focus, $scope.focus);
                    $location.path('/profile');
                };
            }

            // third app transfer and parse method
            function setUser() {
                /**
                 * queryIndex: document.referrer.indexOf('?')
                 * url: queryIndex === -1 ? document.referrer : document.referrer.substring(0, queryIndex)
                 * backUrl: url + '#home/?user=' + obj.user
                 */
                var query = Helper.getQueryStringArgs();
                if (query.user) {
                    var user = JSON.parse(query.user);
                    user.phone && (UserService.user = JSON.parse(query.user));
                    $location.path('/home?').replace();
                }
            }

            function moveShim(dir) {
                var curFocus = $scope.entry[$scope.focus.currentId];
                if (curFocus['move'][dir] !== -1)
                    $scope.focus.currentId = curFocus['move'][dir];
            }

            function globalAction() {
                if ($scope.panel.show)
                    return false;
                if (event.keyCode === KEY.BACK) {
                    Helper.platformBack(event, 'back', false, function () {
                        // location.href = config.returnUrl;
                        history.go(-2);
                        Helper.opStorage($scope).remove([$scope.cache.focus]);
                    });
                }
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', globalAction);
            });
        }
    ]
);